package com.demo.service.impl;

import com.demo.service.FileHandleService;
import com.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author gy
 * @date 2023/2/10
 */
@Service
public class FileHandleServiceImpl implements FileHandleService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String uploadFiles(MultipartFile file, String absolutePath) {
        //保存路径 服务器文件路径
//      String absolutePath = "C:\\FileTest\\";

        if (file.isEmpty()) {
            return "上传文件不存在 请重新上传";
        }
        //文件上传
        //获取上传文件名,包含后缀
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String oldFileName = originalFilename.replace(fileSuffix, "");
        //保存的文件名 or 避免文件重复名称
        String newFileName = UUID.randomUUID() + oldFileName + fileSuffix;

        // todo 附件存放路径 + sitecode + 当天日期 + 学员id
        absolutePath = absolutePath + "yszx\\" + getFileDate() + "\\loginId\\";

        // 判断文件夹是否存在，如果不存在则创建
        File dir = new File(absolutePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //生成保存文件
        File uploadFile = new File(absolutePath + newFileName);
        //将上传文件保存到路径
        try {
            file.transferTo(uploadFile);

            // todo 需要将上传文件的全路径保存到数据库，便于管理端进行下载 也就是下载接口的参数
            // 保存缓存：参数：缓存key、value、超时时间
            redisUtil.set("loginId", absolutePath + newFileName);

            // --------------------------
            return "文件已上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传服务器失败 请联系管理员";
        }

    }

    @Override
    public String downLoad(HttpServletResponse response, String filesUrl) throws UnsupportedEncodingException {

//        filesUrl =  redisUtil.getKey("loginId");
//        filesUrl = redisUtil.get("loginId").toString();


        String filename = getUrlFileName(filesUrl);
        File file = new File(filesUrl);
        //判断文件父目录是否存在
        if (file.exists()) {
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download"); // 设置强制下载。application/force-download
            // 将文件依附在头文件中 设置响应头、以附件形式打开文件 文件名包含中文时需要进行中文编码，否则会出现乱码问题
            response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            byte[] buffer = new byte[1024];
            //文件输入流
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            //输出流
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取Url路径中文件名
     *
     * @param url
     * @return
     */
    public static String getUrlFileName(String url) {
        File tempFile = new File(url.trim());
        String fileName = tempFile.getName();
        return fileName;

    }

    /**
     * 获取文件大小 转换为  M
     *
     * @param file 文件
     * @return M
     */
    public static Double fileSize(MultipartFile file) {
        long size = file.getSize();
        Double fileSize = size * 0.00000095367432;
        return fileSize;
    }

    /**
     * 获取文件服务器绝对路径
     * 路径参数拼接
     *
     * @param file 文件
     * @param path 服务器路径
     * @return 路径
     */
    public static String getLocalPath(MultipartFile file, String path) {
        String originalFilename = file.getOriginalFilename();
        String localPath = path + originalFilename;
        return localPath;
    }

    public static String getFileDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }
}
